package cn.iocoder.yudao.module.dify.service.difyChat;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import io.github.imfangs.dify.client.DifyChatClient;
import io.github.imfangs.dify.client.callback.ChatStreamCallback;
import io.github.imfangs.dify.client.enums.ResponseMode;
import io.github.imfangs.dify.client.event.ErrorEvent;
import io.github.imfangs.dify.client.event.MessageEndEvent;
import io.github.imfangs.dify.client.event.MessageEvent;
import io.github.imfangs.dify.client.exception.DifyApiException;
import io.github.imfangs.dify.client.model.chat.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Dify文件处理跟踪 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DifyChatRobotServiceImpl implements DifyChatRobotService {

    @Autowired
    private DifyChatClient difyChatClient;

    @Override
    public AppParametersResponse getAppParameters(Long userId) throws DifyApiException, IOException {
        AppParametersResponse appParameters = difyChatClient.getAppParameters();
        return appParameters;
    }

    @Override
    public String chatRobotCreat(Long userId) throws DifyApiException, IOException {
        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query("创建对话")
                .user(userId.toString())
                .conversationId(null)
                .responseMode(ResponseMode.BLOCKING)
                .build();
        return difyChatClient.sendChatMessage(message).getConversationId();
    }

    @Override
    public Flux<CommonResult<String>> chatRobotStreaming(String conversationDifyId, String query, Long userId) throws DifyApiException, IOException {
        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query(query)
                .inputs(new HashMap<>())
                .user(userId.toString())
                .conversationId(conversationDifyId)
                .responseMode(ResponseMode.STREAMING)
                .build();
        // 创建 Sinks.Many 用于推送数据
        Sinks.Many<CommonResult<String>> sink = Sinks.many().multicast().onBackpressureBuffer();
        // 发送流式消息
        difyChatClient.sendChatMessageStream(message, new ChatStreamCallback() {
            @Override
            public void onMessage(MessageEvent event) {
                sink.tryEmitNext(CommonResult.success(event.getAnswer()));  // 推送数据到 Flux
            }

            @Override
            public void onMessageEnd(MessageEndEvent event) {
                sink.tryEmitComplete();  // 结束流
            }

            @Override
            public void onError(ErrorEvent event) {
                sink.tryEmitError(new RuntimeException(event.getMessage()));  // 错误处理
            }

            @Override
            public void onException(Throwable throwable) {
                sink.tryEmitError(throwable);  // 异常处理
            }
        });
        // 返回 Flux<String>
        return sink.asFlux();
    }

    @Override
    public ConversationListResponse chatConversationList(Long userId) throws DifyApiException, IOException {
        ConversationListResponse conversations = difyChatClient.getConversations(userId.toString(), null, 100, null);
        return conversations;
    }


    @Override
    public MessageListResponse chatMessageList(String conversationDifyId, Long userId) throws DifyApiException, IOException {
        MessageListResponse conversations = difyChatClient.getMessages(conversationDifyId, userId.toString(), null, 100);
        //下一页
        if (ObjectUtil.isNotEmpty(conversations) && conversations.getHasMore()) {
            List<MessageListResponse.Message> data = chatMessageNextPage(conversations.getData(), conversationDifyId, userId);
            conversations.setData(data);
        }
        return conversations;
    }

    //对话下一页
    private List<MessageListResponse.Message> chatMessageNextPage(List<MessageListResponse.Message> conversations, String conversationDifyId, Long userId) throws DifyApiException, IOException {
        //下一页
        String lastId = conversations.get(conversations.size() - 1).getId();
        MessageListResponse messages = difyChatClient.getMessages(conversationDifyId, userId.toString(), lastId, 100);
        if (ObjectUtil.isNotEmpty(messages) && messages.getHasMore()) {
            chatMessageNextPage(messages.getData(), conversationDifyId, userId);
        }
        conversations.addAll(messages.getData());
        return conversations;
    }

    @Override
    public Boolean deleteDifyConversation(String conversationDifyId, Long userId) throws DifyApiException, IOException {
        difyChatClient.deleteConversation(conversationDifyId, userId.toString());
        return true;
    }

    @Override
    public Boolean difyConversationRename(String conversationDifyId, Long userId, String name) throws DifyApiException, IOException {
        Conversation conversation = difyChatClient.renameConversation(conversationDifyId, name, false, userId.toString());
        return true;
    }


}